package com.phone580.app.model;

import java.util.List;

import com.phone580.app.Constant;
import com.phone580.app.MainApplication;
import com.phone580.app.dao.DownloadInfoDao;
import com.phone580.app.entity.DownloadInfoEntity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class DownloadManagerModel {
	private Context context;
	private DownloadInfoDao dao;

	public DownloadManagerModel(Context context) {
		this.context = context;
		this.dao = new DownloadInfoDao(context);
	}

	public List<DownloadInfoEntity> getUnfinish() {
		return dao.fetchUnFinished();
	}
	
	public List<DownloadInfoEntity> getfinished() {
		return dao.fetchFinished();
	}
	
	public long addDownload (DownloadInfoEntity entity) {
		return dao.addItem(entity);
	}
	
	public DownloadInfoEntity getDownloadInfo (long id) {
		return dao.fetchById(id);
	}
	
	public void updateStatus(DownloadInfoEntity info) {
		dao.updateStatus(info);
	}
	
	public void updateCompleteSize(long id, int size) {
		dao.updateCompleteSize(id, size);
	}
	
//	public void updateFileSize(long id, int size) {
//		dao.updateFileSize(id, size);
//	}
	
	public int checkIsExist(String url) {
		return dao.isExist(url);
	}
	
	public String createNewFileName(String fileName, int count) {
		String newName = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")" + ".apk";
		return newName;
	}
	
	public String getFileName(String url) {
		return url.substring(url.lastIndexOf("=") + 1, url.length());
	}
	
	public void remove(long id) {
		dao.remove(id);
	}
	
//	public boolean isDownloading(String url) {
//		return dao.isDownloading(url);
//	}
	
	public boolean isDownloading(String url) {
		MainApplication app = (MainApplication)context.getApplicationContext();
		List<DownloadInfoEntity> downloadList = app.getDownloadList();
		for (DownloadInfoEntity info : downloadList) {
			if (url.equals(info.getUrl())) {
				return true;
			}
		}
		return false;
	}
	
	public void saveDownloadList(List<DownloadInfoEntity> list) {
		SQLiteDatabase sql = DownloadInfoDao.getSqLiteDatabase(context);
		try {
			sql.beginTransaction();
			for (DownloadInfoEntity info : list) {
				if (info.getStatus() == Constant.DOWNLOAD_CANCEL) {
					continue;
				}
				dao.updateItem(sql, info);
			}
			sql.setTransactionSuccessful();
		} catch (SQLiteException ex) {
			ex.printStackTrace();
		} finally {
			sql.endTransaction();
			sql.close();
		}
	}
	
}
